import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI, getUserProfileAPI, getUserPhotoAPI } from '@/api'
import { Message } from 'element-ui'
const getDefaultState = () => {
  return {
    token: getToken(), // 存放token
    userInfo: {}
  }
}
const state = getDefaultState()

const mutations = {
  // 数据初始化
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 新增
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  // 删除
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },
  // 新增用户信息
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
    // console.log(state.userInfo)
  },
  REMOVE_USERINFO: (state) => {
    state.userInfo = {}
  }

}

const actions = {
  // 登录逻辑-封装
  async loginAPIActions({ commit }, value) {
    try {
      // 发起请求
      const res = await loginAPI(value)
      // 我们只需要token, 保存到上面的vuex中
      commit('SET_TOKEN', res.data)
      // 逻辑页面还在接收数组, 外面写成功/失败的逻辑, 所以这里要把数组返回出去
      // return到actions调用的地方(login/index.vue)
      Message.success(res.message)
      return res
    } catch (err) {
      return Promise.reject(err)
    }
  },
  // 获取用户信息
  async getUserProfileAPIActions({ commit }) {
    try {
      // 发起请求，调用接口
      const userInfo = await getUserProfileAPI()
      // console.log(userInfo)
      const avatar = await getUserPhotoAPI(userInfo.data.userId)
      console.log(avatar)
      const userObj = { ...userInfo.data, ...avatar.data }
      // console.log(userObj)
      // 提交给mutations中的SET_USERINFO
      commit('SET_USERINFO', userObj)
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 退出登录
  logOut({ commit }) {
    commit('REMOVE_TOKEN')
    commit('REMOVE_USERINFO')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

